import 'package:flutter/foundation.dart';
import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import 'package:flutter_taotaoshipin/app/app_controller.dart';
import 'package:flutter_taotaoshipin/pages/drama/drama_routes.dart';
import 'package:flutter_taotaoshipin/pages/recommend/recommend_controller.dart';
import 'package:flutter_taotaoshipin/player/flick_multi_player.dart';
import 'package:flutter_taotaoshipin/routes/app_routes.dart';
import 'package:flutter_taotaoshipin/util/format_utils.dart';
import 'package:flutter_taotaoshipin/widget/load_image.dart';
import 'package:get/get.dart';
import 'package:visibility_detector/visibility_detector.dart';

class RecommendPage extends StatefulWidget {
  const RecommendPage({Key? key}) : super(key: key);

  @override
  State<RecommendPage> createState() => _RecommendPageState();
}

class _RecommendPageState extends State<RecommendPage>
    with AutomaticKeepAliveClientMixin {
  final controller = Get.find<RecommendController>();
  final state = Get.find<RecommendController>().state;

  @override
  bool get wantKeepAlive => true;

  @override
  Widget build(BuildContext context) {
    super.build(context);
    return Scaffold(
      backgroundColor: Colors.black,
      body: VisibilityDetector(
        key: ObjectKey(controller.flickMultiManager),
        onVisibilityChanged: (visibility) {
          if (visibility.visibleFraction == 0 && mounted) {
            // 进入后台暂停播放
            controller.flickMultiManager.pause();
          }
        },
        child: SizedBox.expand(
          child: Stack(
            children: [
              _buildVideoPlayer(),
            ],
          ),
        ),
      ),
    );
  }

  _buildVideoPlayer() {
    return GetBuilder<RecommendController>(
      id: 'recommendDramaList',
      builder: (controller) {
        if (state.recommendDramaList.isEmpty) {
          return Center(child: CircularProgressIndicator());
        } else {
          return PageView.builder(
            physics: const ClampingScrollPhysics(),
            controller: controller.pageController,
            scrollDirection: Axis.vertical,
            onPageChanged: controller.onPageChanged,
            itemCount: state.recommendDramaList.length,
            itemBuilder: (context, index) {
              return FutureBuilder(
                future: controller.startLoadVideoUrlData(index),
                builder: (context, snapshot) {
                  List<Widget> children;
                  if (snapshot.hasData) {
                    var mainInfoEntity = state.mainInfoEntityMap[index];
                    children = <Widget>[
                      if (mainInfoEntity?.isSelf == 1)
                        FlickMultiPlayer(
                          url: state.videoUrlMap[index]?.vodPlayInfo
                                  ?.mainPlayUrl ??
                              '',
                          flickMultiManager: controller.flickMultiManager,
                          progressBarBottomOffset: 0,
                          onVideoEnd: () {
                            if (Get.routing.current == AppRoutes.rootTab) {
                              // 跳转视频详情页
                              Get.toNamed(DramaRoutes.detail, arguments: {
                                'id': mainInfoEntity?.id,
                                'title': '',
                                'sort': 2,
                              });
                            }
                          },
                        )
                      // else
                      //   UiKitView(
                      //     viewType: TtspPangrowthConstants.playletTypeId,
                      //     layoutDirection: TextDirection.ltr,
                      //     creationParams: <String, dynamic>{
                      //       'skitId': state.dramaListEntityList.first.vid,
                      //       'episode': 1,
                      //       'bottomOffset': 0,
                      //     },
                      //     creationParamsCodec: const StandardMessageCodec(),
                      //   ),
                    ];
                  } else if (snapshot.hasError) {
                    children = <Widget>[
                      const Icon(
                        Icons.error_outline,
                        color: Colors.red,
                        size: 60,
                      ),
                      Padding(
                        padding: const EdgeInsets.only(top: 16),
                        child: Text(
                          'Error: ${snapshot.error}',
                          style: TextStyle(color: Colors.white),
                        ),
                      ),
                    ];
                  } else {
                    children = <Widget>[
                      const CircularProgressIndicator(),
                    ];
                  }
                  children.addAll([
                    Positioned(
                        right: 26, bottom: 180, child: _buildRights(index)),
                    Positioned(
                        left: 0,
                        right: 0,
                        bottom: 15,
                        child: _buildInfos(index)),
                    Positioned(
                        left: 0, top: 0, right: 0, child: _buildTops(index)),
                  ]);

                  return Stack(
                    alignment: Alignment.center,
                    children: children,
                  );
                },
              );
            },
          );
        }
      },
    );
  }

  _buildInfos(int index) {
    var entity = state.mainInfoEntityMap[index];
    return GestureDetector(
      onTap: () {
        // 跳转视频详情页
        Get.toNamed(DramaRoutes.detail, arguments: {
          'id': entity?.id,
          'title': '',
        });
      },
      child: Padding(
        padding: const EdgeInsets.fromLTRB(16, 16, 26, 16),
        child: Row(
          children: [
            Expanded(
              child: Text(
                entity?.title ?? '',
                style: const TextStyle(
                  fontSize: 16,
                  fontWeight: FontWeight.w400,
                  color: Colors.white,
                ),
                maxLines: 2,
                overflow: TextOverflow.ellipsis,
              ),
            ),
            GestureDetector(
              onTap: () {
                // 跳转视频详情页
                Get.toNamed(DramaRoutes.detail, arguments: {
                  'id': entity?.id,
                  'title': '',
                  'sort': 2,
                });
              },
              child: LoadAssetImage(
                'drama/detail/fullscreen',
                width: 34,
                height: 34,
              ),
            ),
          ],
        ),
      ),
    );
  }

  _buildRights(int index) {
    return GetBuilder<RecommendController>(
        id: 'dramaInteractInfoEntity',
        builder: (controller) {
          var entity = state.dramaInteractInfoEntityMap[index];
          return Column(
            children: [
              _buildRightItem(
                imageName: (entity?.collectBool ?? false)
                    ? 'drama/detail/collect_sel'
                    : 'drama/detail/collect',
                text: (entity?.collectBool ?? false) ? '已追' : '追剧',
                onTap: () {
                  controller.userCollectBtnClicked(index);
                },
              ),
              SizedBox(height: 26),
              GetBuilder<AppController>(builder: (appController) {
                var text = countFormat(entity?.share ?? 0);
                return _buildRightItem(
                  imageName: 'drama/detail/share',
                  text: '分享',
                  onTap: () {
                    appController.appProfile.shareBtnClicked = true;
                    appController.updateAppProfile(appController.appProfile);
                    controller.userShareBtnClicked(index);
                  },
                  isRed: !appController.appProfile.shareBtnClicked!,
                );
              }),
            ],
          );
        });
  }

  _buildRightItem({
    required String imageName,
    String? text,
    Function()? onTap,
    bool isRed = false,
  }) {
    return InkWell(
      onTap: onTap,
      child: Container(
        child: Stack(
          children: [
            Column(
              children: [
                LoadAssetImage(
                  imageName,
                  width: 34,
                ),
                if (text != null)
                  Padding(
                    padding: const EdgeInsets.only(top: 3),
                    child: Text(
                      text,
                      style: const TextStyle(
                        color: Colors.white,
                        fontSize: 16,
                        fontWeight: FontWeight.w400,
                      ),
                    ),
                  ),
              ],
            ),
            if (isRed)
              Positioned(
                top: 0,
                right: 0,
                child: Container(
                  width: 8,
                  height: 8,
                  decoration: BoxDecoration(
                    color: Colors.red,
                    borderRadius: BorderRadius.circular(5),
                  ),
                ),
              ),
          ],
        ),
      ),
    );
  }

  _buildTops(int index) {
    return Container(
      child: Column(
        children: [],
      ),
    );
  }
}
